import requests
import base64

from flask import Blueprint, jsonify, request
from app.db.main import con_my_sql

# Dify API 配置
DIFY_API_KEY = 'app-tgRILgKS7sh4b26tg4dmyyYh'
DIFY_USER_ID = 'SharkBrother'
DIFY_BASE_URL = 'http://yaoai.icu:15644/v1'

# 创建蓝图
bp = Blueprint('analysis', __name__)

# 分析接口
@bp.route('/', methods=['POST', 'GET'])
def analysis():
    file_id = None
    if request.method == 'POST':
        file = request.files.get('files')

        if not file:
            return jsonify({'message': '请选择文件'})

        else:
            file_id, file_content = _upload_file(file, DIFY_USER_ID)

            sql_code = """
            UPDATE files SET fileId = %s, fileContent = %s 
            WHERE route = 'analysis'
            """
            con_my_sql(sql_code, (file_id, file_content))
            # print("sql_code: ", sql_code)

            return jsonify({
                'message': '文件上传成功',
                'file_id': file_id,
            })

    elif request.method == 'GET':
        file_id = request.args.get('file_id')
        if not file_id or len(file_id) == 0:
            sql_code = "SELECT * FROM files WHERE route = 'analysis'"
            cursor = con_my_sql(sql_code)
            mysql_output = cursor.fetchall()[0]

            if mysql_output.get('fileId') is not None:
                file_content = mysql_output.get('fileContent')
                base64_data = base64.b64encode(file_content).decode('utf-8')
                message = mysql_output.get('message')

                return jsonify({
                    'fileId': mysql_output.get('fileId'),
                    'fileContent': base64_data,
                    'message': message,
                })

            return jsonify({'message': '请提供文件'})
        
        response = _run_workflow(file_id, DIFY_USER_ID)
        # print(response.get('data').get('outputs').get('text'))

        sql_code = """
        UPDATE files SET message = %s 
        WHERE route = 'analysis'
        """
        con_my_sql(sql_code, (response.get('data').get('outputs').get('text'), ))
        
        return jsonify({'message': response.get('data').get('outputs').get('text')})

# 运行工作流
def _run_workflow(file_id, user, response_mode="blocking"):
    workflow_url = DIFY_BASE_URL + "/workflows/run"
    headers = {
        "Authorization": f"Bearer {DIFY_API_KEY}",
        "Content-Type": "application/json"
    }

    data = {
        "inputs": {
            "input_document": {
                "transfer_method": "local_file",
                "upload_file_id": file_id,
                "type": "document"
            }
        },
        "response_mode": response_mode,
        "conversation_id": "",
        "user": user
    }

    try:
        print("运行工作流...")
        response = requests.post(workflow_url, headers=headers, json=data)
        if response.status_code == 200:
            print("工作流执行成功")
            return response.json()
        else:
            print(f"工作流执行失败，状态码: {response.status_code}")
            return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code} {response.text}"}
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return {"status": "error", "message": str(e)}

# 上传文件到 Dify
def _upload_file(file, user):
    upload_url = DIFY_BASE_URL + "/files/upload"
    file_content = file.read()

    headers = {
        "Authorization": f"Bearer {DIFY_API_KEY}",
    }
    
    print("上传文件中...")
    files = {
        "file": (file.filename, file_content, 'application/pdf')
    }
    data = {
        "user": user,
        "type": "PDF"
    }
    
    response = requests.post(upload_url, headers=headers, data=data, files=files)
    if response.status_code == 201:  # 201 表示创建成功
        print("文件上传成功")
        print(response.json().get("id"))
        return response.json().get("id"), file_content  # 获取上传的文件 ID
    else: 
        print(f"文件上传失败，状态码: {response.status_code} {response.text}")
        return None, None
